package com.winit.project.task;

import com.winit.common.util.ConfigUtil;
import com.winit.project.core.branch.Project;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by wangjian on 16/8/9.
 * 单例
 */
public class BuildTaskContainer {

    private BuildTaskContainer(){}

    private static final BuildTaskContainer BUILD_TASK_CONTAINER = new BuildTaskContainer();

    public static BuildTaskContainer getInstance(){
        return BUILD_TASK_CONTAINER;
    }

    public static ExecutorService BuildTaskPool = Executors.newFixedThreadPool(Integer.parseInt(ConfigUtil.getValue("build_task_max_count")));

    private static Map<String,BuildTask> buildTaskMap = new HashMap<>();

    private static final Logger logger = LoggerFactory.getLogger(BuildTaskContainer.class);

    public void addBuildTask(BuildTask buildTask) throws Exception{
        String projectName = buildTask.getProjectName();
        Project project = buildTask.getProject();
        if(project.isOnBuild()){
            logger.error("工程正在构建中,请稍后......;projectName="+projectName);
            throw new Exception("当前工程或关联jar工程正在构建中,请稍后......");
        }
        project.updateBuildStatus(BuildStatusEnum.IN_QUEUE,projectName);
        project.updateDependencyProjectStatus(BuildStatusEnum.IN_QUEUE);
        logger.info("BuildTaskContainer:添加构建任务.projectName="+projectName);
        if(this.buildTaskMap.containsKey(projectName)){
            logger.error("BuildTaskContainer:添加任务,工程正在构建中.projectName="+projectName);
            throw new Exception("BuildTaskContainer:添加任务,工程正在构建中.projectName="+projectName);
        }
        this.buildTaskMap.put(projectName,buildTask);
        this.BuildTaskPool.submit(buildTask);
    }

    public void removeTask(String projectName){
        logger.info("BuildTaskContainer:线程关闭,删除buildTaskMap内对象.projectName="+projectName);
        if(!this.buildTaskMap.containsKey(projectName)){
            logger.info("BuildTaskContainer:线程关闭,删除buildTaskMap内对象,对象不存在.projectName="+projectName);
            return;
        }
        this.buildTaskMap.remove(projectName);
    }
}
